import 'package:flutter/material.dart';

enum SwipeDirection { left, right }

typedef SwipeDeleteCallback = void Function(int index, SwipeDirection direction, Widget deletedChild);

class StackedSwipeCarousel extends StatefulWidget {
  final List<Widget> children;
  final SwipeDeleteCallback? onSwipeDelete;
  final double swipeThreshold;
  final Duration animationDuration;
  final double itemWidth;
  final double itemHeight;
  final int visibleCount;
  final double stackOffset;
  final double scaleStep;
  final Color deleteBackgroundColor;
  final IconData leftSwipeIcon;
  final IconData rightSwipeIcon;
  final Color swipeIconColor;
  final double swipeIconSize;
  final Curve animationCurve;
  final double rotationAngle;

  const StackedSwipeCarousel({
    Key? key,
    required this.children,
    this.onSwipeDelete,
    this.swipeThreshold = 0.3,
    this.animationDuration = const Duration(milliseconds: 300),
    this.itemWidth = 300.0,
    this.itemHeight = 400.0,
    this.visibleCount = 3,
    this.stackOffset = 8.0,
    this.scaleStep = 0.05,
    this.deleteBackgroundColor = Colors.red,
    this.leftSwipeIcon = Icons.close,
    this.rightSwipeIcon = Icons.favorite,
    this.swipeIconColor = Colors.white,
    this.swipeIconSize = 32.0,
    this.animationCurve = Curves.easeOutCubic,
    this.rotationAngle = 15.0,
  }) : super(key: key);

  @override
  State<StackedSwipeCarousel> createState() => _StackedSwipeCarouselState();
}

class _StackedSwipeCarouselState extends State<StackedSwipeCarousel>
    with TickerProviderStateMixin {
  late List<Widget> _items;
  late AnimationController _swipeAnimationController;
  late AnimationController _stackAnimationController;

  int _currentTopIndex = 0;
  double _dragDistance = 0.0;
  double _dragAngle = 0.0;
  bool _isDragging = false;
  bool _isAnimating = false; // 新增：防止动画期间的状态冲突

  @override
  void initState() {
    super.initState();
    _items = List.from(widget.children);
    _swipeAnimationController = AnimationController(
      duration: widget.animationDuration,
      vsync: this,
    );
    _stackAnimationController = AnimationController(
      duration: widget.animationDuration,
      vsync: this,
    );
  }

  @override
  void dispose() {
    _swipeAnimationController.dispose();
    _stackAnimationController.dispose();
    super.dispose();
  }

  void _handleSwipeComplete(SwipeDirection direction) async {
    if (_currentTopIndex < _items.length) {
      final deletedChild = _items[_currentTopIndex];
      final deletedIndex = _currentTopIndex;

      // 执行堆叠动画
      await _stackAnimationController.forward();

      setState(() {
        _currentTopIndex++;
        _dragDistance = 0.0;
        _dragAngle = 0.0;
        _isAnimating = false; // 重置动画状态
      });

      // 重置动画控制器
      _swipeAnimationController.reset();
      _stackAnimationController.reset();

      // 调用删除回调
      widget.onSwipeDelete?.call(deletedIndex, direction, deletedChild);
    }
  }

  List<Widget> _buildStackedCards() {
    List<Widget> stackedCards = [];

    // 计算可见卡片的数量
    final visibleCount = widget.visibleCount.clamp(1, _items.length - _currentTopIndex);

    for (int i = visibleCount - 1; i >= 0; i--) {
      final cardIndex = _currentTopIndex + i;
      if (cardIndex >= _items.length) continue;

      final isTopCard = i == 0;
      final stackLevel = i;

      stackedCards.add(
        _buildStackedCard(
          child: _items[cardIndex],
          stackLevel: stackLevel,
          isTopCard: isTopCard,
          cardIndex: cardIndex,
        ),
      );
    }

    return stackedCards;
  }

  Widget _buildStackedCard({
    required Widget child,
    required int stackLevel,
    required bool isTopCard,
    required int cardIndex,
  }) {
    // 计算卡片的变换属性
    double scale = 1.0 - (stackLevel * widget.scaleStep);
    double yOffset = stackLevel * widget.stackOffset;

    // 如果正在拖拽顶层卡片，其他卡片需要相应动画
    if (!isTopCard && _isDragging) {
      final progress = (_dragDistance.abs() / (widget.itemWidth * widget.swipeThreshold)).clamp(0.0, 1.0);
      scale = (1.0 - ((stackLevel - 1) * widget.scaleStep)) + (widget.scaleStep * progress);
      yOffset = ((stackLevel - 1) * widget.stackOffset) + (widget.stackOffset * (1 - progress));
    }

    Widget cardWidget = Container(
      width: widget.itemWidth,
      height: widget.itemHeight,
      child: child,
    );

    // 顶层卡片处理拖拽和滑动动画
    if (isTopCard) {
      cardWidget = _buildTopCard(cardWidget);
    }

    return AnimatedBuilder(
      animation: _stackAnimationController,
      builder: (context, _) {
        double animatedScale = scale;
        double animatedYOffset = yOffset;

        // 堆叠动画：当顶层卡片被移除时，其他卡片向前移动
        if (_stackAnimationController.isAnimating && !isTopCard) {
          final animation = CurvedAnimation(
            parent: _stackAnimationController,
            curve: widget.animationCurve,
          );

          final targetScale = 1.0 - ((stackLevel - 1) * widget.scaleStep);
          final targetYOffset = (stackLevel - 1) * widget.stackOffset;

          animatedScale = Tween<double>(
            begin: scale,
            end: targetScale,
          ).animate(animation).value;

          animatedYOffset = Tween<double>(
            begin: yOffset,
            end: targetYOffset,
          ).animate(animation).value;
        }

        return Positioned(
          top: animatedYOffset,
          child: Transform.scale(
            scale: animatedScale,
            child: cardWidget,
          ),
        );
      },
    );
  }

  Widget _buildTopCard(Widget child) {
    return GestureDetector(
      onPanStart: _handlePanStart,
      onPanUpdate: _handlePanUpdate,
      onPanEnd: _handlePanEnd,
      child: AnimatedBuilder(
        animation: _swipeAnimationController,
        builder: (context, _) {
          double animatedDistance = _dragDistance;
          double animatedAngle = _dragAngle;

          // 如果正在执行滑动动画
          if (_swipeAnimationController.isAnimating) {
            final animation = CurvedAnimation(
              parent: _swipeAnimationController,
              curve: widget.animationCurve,
            );

            // 根据滑动方向决定最终位置
            final direction = _dragDistance > 0 ? 1.0 : -1.0;
            final targetDistance = direction * widget.itemWidth * 2;
            final targetAngle = direction * widget.rotationAngle;

            animatedDistance = Tween<double>(
              begin: _dragDistance,
              end: targetDistance,
            ).animate(animation).value;

            animatedAngle = Tween<double>(
              begin: _dragAngle,
              end: targetAngle,
            ).animate(animation).value;
          }

          return Transform.translate(
            offset: Offset(animatedDistance, 0),
            child: Transform.rotate(
              angle: animatedAngle * (3.14159 / 180),
              child: Stack(
                children: [
                  // 背景指示器
                  if (_isDragging) _buildSwipeIndicator(),
                  // 卡片内容
                  child,
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  Widget _buildSwipeIndicator() {
    final isLeftSwipe = _dragDistance < 0;
    final progress = (_dragDistance.abs() / (widget.itemWidth * widget.swipeThreshold)).clamp(0.0, 1.0);

    return Positioned.fill(
      child: Container(
        decoration: BoxDecoration(
          color: (isLeftSwipe ? Colors.red : Colors.green).withOpacity(progress * 0.3),
          borderRadius: BorderRadius.circular(16),
        ),
        child: Center(
          child: Icon(
            isLeftSwipe ? widget.leftSwipeIcon : widget.rightSwipeIcon,
            color: widget.swipeIconColor.withOpacity(progress),
            size: widget.swipeIconSize + (progress * 16),
          ),
        ),
      ),
    );
  }

  void _handlePanStart(DragStartDetails details) {
    if (_isAnimating) return; // 防止动画期间开始新的拖拽
    _isDragging = true;
    _swipeAnimationController.stop();
  }

  void _handlePanUpdate(DragUpdateDetails details) {
    if (!_isDragging || _isAnimating) return; // 防止动画期间更新拖拽

    setState(() {
      _dragDistance += details.delta.dx;
      _dragDistance = _dragDistance.clamp(-widget.itemWidth, widget.itemWidth);

      // 计算旋转角度
      final progress = _dragDistance / widget.itemWidth;
      _dragAngle = progress * widget.rotationAngle;
    });
  }

  void _handlePanEnd(DragEndDetails details) {
    if (!_isDragging || _isAnimating) return; // 防止动画期间结束拖拽

    _isDragging = false;
    _isAnimating = true; // 标记开始动画

    final threshold = widget.itemWidth * widget.swipeThreshold;

    if (_dragDistance.abs() > threshold) {
      // 达到删除阈值，执行删除动画
      final direction = _dragDistance > 0 ? SwipeDirection.right : SwipeDirection.left;
      _animateSwipeComplete(direction);
    } else {
      // 未达到阈值，回弹
      _animateSnapBack();
    }
  }

  void _animateSwipeComplete(SwipeDirection direction) async {
    await _swipeAnimationController.forward();
    _handleSwipeComplete(direction);
  }

  void _animateSnapBack() async {
    // 修复：直接使用 Tween 动画而不是监听器
    final distanceAnimation = Tween<double>(
      begin: _dragDistance,
      end: 0.0,
    ).animate(CurvedAnimation(
      parent: _swipeAnimationController,
      curve: widget.animationCurve,
    ));

    final angleAnimation = Tween<double>(
      begin: _dragAngle,
      end: 0.0,
    ).animate(CurvedAnimation(
      parent: _swipeAnimationController,
      curve: widget.animationCurve,
    ));

    // 使用 AnimatedBuilder 来更新状态，避免监听器冲突
    animationStatusListener(AnimationStatus status) {
      if (status == AnimationStatus.completed) {
        _swipeAnimationController.removeStatusListener(animationStatusListener);
        setState(() {
          _dragDistance = 0.0;
          _dragAngle = 0.0;
          _isAnimating = false;
        });
        _swipeAnimationController.reset();
      }
    }

    _swipeAnimationController.addStatusListener(animationStatusListener);

    // 在动画过程中更新拖拽距离和角度
    animationListener() {
      if (mounted) {
        setState(() {
          _dragDistance = distanceAnimation.value;
          _dragAngle = angleAnimation.value;
        });
      }
    }

    _swipeAnimationController.addListener(animationListener);

    await _swipeAnimationController.forward();

    // 清理监听器
    _swipeAnimationController.removeListener(animationListener);
  }

  @override
  Widget build(BuildContext context) {
    if (_currentTopIndex >= _items.length) {
      return Container(
        width: widget.itemWidth,
        height: widget.itemHeight,
        decoration: BoxDecoration(
          color: Colors.grey[100],
          borderRadius: BorderRadius.circular(16),
          border: Border.all(color: Colors.grey[300]!),
        ),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                Icons.check_circle_outline,
                size: 48,
                color: Colors.grey[400],
              ),
              SizedBox(height: 16),
              Text(
                '全部完成!',
                style: TextStyle(
                  fontSize: 18,
                  color: Colors.grey[600],
                  fontWeight: FontWeight.w500,
                ),
              ),
            ],
          ),
        ),
      );
    }

    return Container(
      width: widget.itemWidth,
      height: widget.itemHeight + (widget.visibleCount * widget.stackOffset),
      child: Stack(
        alignment: Alignment.topCenter,
        children: _buildStackedCards(),
      ),
    );
  }
}
// 示例使用
class StackedSwipeDemo extends StatefulWidget {
  @override
  State<StackedSwipeDemo> createState() => _StackedSwipeDemoState();
}

class _StackedSwipeDemoState extends State<StackedSwipeDemo> {
  List<Widget> _cards = [];
  List<String> _swipeHistory = [];

  @override
  void initState() {
    super.initState();
    _generateCards();
  }

  void _generateCards() {
    final colors = [
      [Color(0xFFFF6B6B), Color(0xFFFF8E53)],
      [Color(0xFF4ECDC4), Color(0xFF44A08D)],
      [Color(0xFF45B7D1), Color(0xFF96C93D)],
      [Color(0xFF9B59B6), Color(0xFF8E44AD)],
      [Color(0xFFE67E22), Color(0xFFD35400)],
      [Color(0xFF1ABC9C), Color(0xFF16A085)],
      [Color(0xFFE74C3C), Color(0xFFC0392B)],
    ];

    _cards = List.generate(7, (index) {
      return Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            colors: colors[index % colors.length],
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
          ),
          borderRadius: BorderRadius.circular(20),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              blurRadius: 10,
              offset: Offset(0, 5),
            ),
          ],
        ),
        child: Padding(
          padding: EdgeInsets.all(24),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                width: 80,
                height: 80,
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.2),
                  shape: BoxShape.circle,
                ),
                child: Icon(
                  Icons.credit_card,
                  size: 40,
                  color: Colors.white,
                ),
              ),
              SizedBox(height: 24),
              Text(
                '卡片 ${index + 1}',
                style: TextStyle(
                  fontSize: 28,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
              SizedBox(height: 12),
              Text(
                '左滑拒绝 • 右滑喜欢',
                style: TextStyle(
                  fontSize: 16,
                  color: Colors.white.withOpacity(0.8),
                ),
              ),
              SizedBox(height: 24),
              Container(
                padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.2),
                  borderRadius: BorderRadius.circular(20),
                ),
                child: Text(
                  '拖拽或滑动我',
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.white,
                  ),
                ),
              ),
            ],
          ),
        ),
      );
    });
  }

  void _handleSwipeDelete(int index, SwipeDirection direction, Widget deletedChild) {
    final action = direction == SwipeDirection.left ? '拒绝' : '喜欢';
    setState(() {
      _swipeHistory.insert(0, '卡片 ${index + 1}: $action');
      if (_swipeHistory.length > 5) {
        _swipeHistory = _swipeHistory.take(5).toList();
      }
    });
  }

  void _resetCards() {
    setState(() {
      _generateCards();
      _swipeHistory.clear();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[50],
      appBar: AppBar(
        title: Text('堆叠滑动卡片'),
        backgroundColor: Colors.transparent,
        elevation: 0,
        actions: [
          IconButton(
            icon: Icon(Icons.refresh),
            onPressed: _resetCards,
          ),
        ],
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            SizedBox(height: 20),
            // 提示文本
            Container(
              margin: EdgeInsets.symmetric(horizontal: 20),
              padding: EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(12),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.05),
                    blurRadius: 5,
                    offset: Offset(0, 2),
                  ),
                ],
              ),
              child: Row(
                children: [
                  Icon(Icons.info_outline, color: Colors.blue),
                  SizedBox(width: 12),
                  Expanded(
                    child: Text(
                      '拖拽顶层卡片左右滑动，观察后面卡片的动画效果',
                      style: TextStyle(fontSize: 14),
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(height: 30),
            // 堆叠卡片组件
            StackedSwipeCarousel(
              children: _cards,
              onSwipeDelete: _handleSwipeDelete,
              visibleCount: 3,
              swipeThreshold: 0.25,
              stackOffset: 12.0,
              scaleStep: 0.06,
              rotationAngle: 12.0,
            ),
            SizedBox(height: 40),
            // 操作历史
            if (_swipeHistory.isNotEmpty) ...[
              Container(
                margin: EdgeInsets.symmetric(horizontal: 20),
                padding: EdgeInsets.all(20),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(16),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.05),
                      blurRadius: 10,
                      offset: Offset(0, 3),
                    ),
                  ],
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Icon(Icons.history, color: Colors.grey[600]),
                        SizedBox(width: 8),
                        Text(
                          '操作历史',
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                            color: Colors.grey[800],
                          ),
                        ),
                      ],
                    ),
                    SizedBox(height: 16),
                    ..._swipeHistory.map((history) => Padding(
                      padding: EdgeInsets.only(bottom: 8),
                      child: Row(
                        children: [
                          Container(
                            width: 6,
                            height: 6,
                            decoration: BoxDecoration(
                              color: Colors.blue,
                              shape: BoxShape.circle,
                            ),
                          ),
                          SizedBox(width: 12),
                          Text(
                            history,
                            style: TextStyle(
                              fontSize: 14,
                              color: Colors.grey[700],
                            ),
                          ),
                        ],
                      ),
                    )).toList(),
                  ],
                ),
              ),
            ],
            SizedBox(height: 40),
          ],
        ),
      ),
    );
  }
}